﻿using System.Collections.Generic;
using System.Reflection;
using Castle.DynamicProxy;

namespace Vasuleg.UIDrive
{
    public class EntityInterceptorImpl : IInterceptor
    {
        private const string GetMethodPrefix = "get_";
        private const string SetMethodPrefix = "set_";

        private readonly object _target;
        private Dictionary<MethodInfo, List<PropGetAction>> _propGetListener;
        private Dictionary<MethodInfo, List<PropSetAction>> _propSetListener;

        public delegate void PropGetAction(string propName, object value);

        public delegate void PropSetAction(string propName, object value);

        public EntityInterceptorImpl(object target)
        {
            _target = target;
        }

        public void AddPropGetListener(string propName, PropGetAction action)
        {
            AddPropGetSetListener(GetMethodPrefix, propName, ref _propGetListener, action);
        }

        public void AddPropSetListener(string propName, PropSetAction action)
        {
            AddPropGetSetListener(SetMethodPrefix, propName, ref _propSetListener, action);
        }

        private void AddPropGetSetListener<T>(string methodPrefix, string propName,
            ref Dictionary<MethodInfo, List<T>> listenerDict, T action)
        {
            if (action == null)
            {
                return;
            }

            if (listenerDict == null)
            {
                listenerDict = new Dictionary<MethodInfo, List<T>>();
            }
            else
            {
                foreach (var (key, value) in listenerDict)
                {
                    if (key.Name == methodPrefix + propName)
                    {
                        value.Add(action);
                        return;
                    }
                }
            }

            MethodInfo keyMethod = null;
            if (methodPrefix == GetMethodPrefix)
            {
                keyMethod = _target.GetType().GetProperty(propName)?.GetMethod;
            }
            else if (methodPrefix == SetMethodPrefix)
            {
                keyMethod = _target.GetType().GetProperty(propName)?.SetMethod;
            }
            if (keyMethod != null)
            {
                listenerDict.Add(keyMethod, new List<T> {action});
            }
        }


        public bool RemovePropSetListener(string propName, PropSetAction action)
        {
            return RemovePropGetSetListener(GetMethodPrefix, propName, _propSetListener, action);
        }


        public bool RemovePropGetListener(string propName, PropGetAction action)
        {
            return RemovePropGetSetListener(SetMethodPrefix, propName, _propGetListener, action);
        }

        private bool RemovePropGetSetListener<T>(string methodPrefix, string propName,
            Dictionary<MethodInfo, List<T>> listenerDict, T action)
        {
            if (listenerDict == null || action == null)
            {
                return false;
            }

            foreach (var (key, value) in listenerDict)
            {
                if (key.Name == methodPrefix + propName)
                {
                    return value.Remove(action);
                }
            }
            return false;
        }


        public virtual void Intercept(IInvocation invocation)
        {
            var method = invocation.Method;
            if (!method.IsSpecialName)
            {
                invocation.Proceed();
                return;
            }
            invocation.Proceed();
            if (_propGetListener != null && _propGetListener.TryGetValue(method, out var actionGetList))
            {
                var propName = GetPropName(method);
                var value = invocation.ReturnValue;
                for (var i = actionGetList.Count - 1; i >= 0; i--)
                {
                    actionGetList[i].Invoke(propName, value);
                }
            }
            else if (_propSetListener != null &&
                     _propSetListener.TryGetValue(method, out var actionSetList))
            {
                var propName = GetPropName(method);
                var value = invocation.GetArgumentValue(0);
                for (var i = actionSetList.Count - 1; i >= 0; i--)
                {
                    actionSetList[i].Invoke(propName, value);
                }
            }
        }

        private static string GetPropName(MethodInfo method)
        {
            var methodName = method.Name;
            var indexOf = methodName.IndexOf('_');
            return methodName.Substring(indexOf + 1);
        }

        public virtual void Destroy()
        {
            _propGetListener?.Clear();
            _propGetListener = null;
            _propSetListener?.Clear();
            _propSetListener = null;
        }
    }
}